#pragma once

#include <iostream>
#include <vector>
#include "InetAddr.hpp"
#include "Mutex.hpp"

class Route
{
private:

void addUser(InetAddr &addr)
{
    LOG(LogLevel::INFO) << "新增一名用户: " << addr.StringAddr();
    _online_users.push_back(addr);
}

bool IsExist(InetAddr &peer)
{
    for(auto user : _online_users)
    {
        if(user == peer)
        {
            return true;
        }
    }
    return false;
}

void DeleteUser(InetAddr &peer)
{
    for(auto iter = _online_users.begin(); iter != _online_users.end(); iter++)
    {
        if(*iter == peer)
        {
            _online_users.erase(iter);
            break;
        }
    }
}

public:
    Route()
    {

    }

    void MessageRoute(int sockfd, const std::string message, InetAddr &peer)
    {
        LockGuard lock(_mutex);
        if(!IsExist(peer))
        {
            addUser(peer);
        }

        if(message == "Quit")
        {
            DeleteUser(peer);
        }

        std::string sendMessage = peer.StringAddr() + "#" + message;

        for(auto &user:_online_users)
        {
            sendto(sockfd, sendMessage.c_str(), sizeof(sendMessage), 0, (const struct sockaddr  *)&user.NetAddr(), sizeof(user.NetAddr()));
        }
    }

    ~Route()
    {

    }
private:
    std::vector<InetAddr> _online_users;
    Mutex _mutex;
};